<template>
  <view class="w-full max-w-[750rpx] mx-auto min-h-screen bg-[#f6f8fa] p-[32rpx] box-border">
    <text class="block text-[56rpx] font-extrabold mb-[48rpx] text-center text-blue-600 drop-shadow">社会经济学信息</text>

    <!-- 数据列表 -->
    <view v-if="!showForm" class="mb-[32rpx]">
      <view class="flex justify-between items-center mb-[24rpx]">
        <text class="text-[32rpx] font-bold">信息列表</text>
        <nut-button type="primary" size="small" class="text-[28rpx]" @click="addRecord">
          新增记录
        </nut-button>
      </view>

      <view v-if="recordList.length === 0" class="text-center py-[80rpx] text-[28rpx] text-gray-500">
        暂无数据，点击新增记录添加信息
      </view>

      <view v-else class="space-y-[24rpx]">
        <view v-for="(record, index) in recordList" :key="record.id || index"
          class="bg-white rounded-[16rpx] p-[24rpx] shadow-sm">
          <view class="flex justify-between items-start mb-[16rpx]">
            <text class="text-[32rpx] font-bold text-gray-800">{{ record.name || '未填写姓名' }}</text>
            <view class="flex gap-[16rpx]">
              <nut-button type="primary" size="mini" @click="editRecord(record, index)">
                编辑
              </nut-button>
              <nut-button type="danger" size="mini" @click="deleteRecord(index)">
                删除
              </nut-button>
            </view>
          </view>

          <view class="grid grid-cols-2 gap-[16rpx] text-[28rpx]">
            <view><text class="text-gray-600">性别：</text>{{ getSexText(record.sex) }}</view>
            <view><text class="text-gray-600">出生日期：</text>{{ record.birthdate || '未填写' }}</view>
            <view><text class="text-gray-600">文化程度：</text>{{ getEduTypeText(record.eduType) }}</view>
            <view><text class="text-gray-600">职业：</text>{{ getJobTypeText(record.jobType) }}</view>
            <view><text class="text-gray-600">婚姻状况：</text>{{ getMarriTypeText(record.marriType) }}</view>
            <view><text class="text-gray-600">电话：</text>{{ record.tel || '未填写' }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 表单 -->
    <view v-if="showForm">
      <view class="flex justify-between items-center mb-[32rpx]">
        <text class="text-[32rpx] font-bold">{{ isEdit ? '编辑信息' : '新增信息' }}</text>
        <nut-button type="default" size="small" @click="cancelForm">
          返回列表
        </nut-button>
      </view>

      <nut-form ref="formRef" :model="form" :rules="formRules" class="max-w-[700rpx] w-full mx-auto box-border">
        <!-- 基本信息 -->
        <view class="mb-[32rpx]">
          <text class="text-[36rpx] font-bold text-blue-600 mb-[24rpx] block">基本信息</text>

          <nut-form-item label="姓名" prop="name" class="mb-[32rpx] text-[32rpx]">
            <nut-input v-model="form.name" placeholder="请输入姓名" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>

          <nut-form-item label="性别" prop="sex" class="mb-[32rpx]">
            <nut-radio-group v-model="form.sex" direction="horizontal">
              <nut-radio :label="1">男</nut-radio>
              <nut-radio :label="0">女</nut-radio>
            </nut-radio-group>
          </nut-form-item>

          <nut-form-item label="出生日期" prop="birthdate" class="mb-[32rpx]">
            <nut-input v-model="form.birthdate" placeholder="请选择出生日期" readonly class="h-[88rpx] text-[32rpx]"
              @click="showCalendar = true" />
            <nut-calendar v-model:visible="showCalendar" v-model="selectedDate" @confirm="onCalendarConfirm"
              @close="showCalendar = false" @select="onCalendarConfirm" title="选择出生日期" :start-date="minDate"
              :end-date="maxDate" :poppable="true" :show-today="true" />
          </nut-form-item>

          <PickerInput v-model="form.idType" :columns="idTypeOptions" label="证件类型" prop="idType" placeholder="请选择证件类型" />

          <nut-form-item label="证件号码" prop="idNumber" class="mb-[32rpx]">
            <nut-input v-model="form.idNumber" placeholder="请输入证件号码" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>

          <nut-form-item label="电话" prop="tel" class="mb-[32rpx]">
            <nut-input v-model="form.tel" placeholder="请输入电话号码" type="tel" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>
        </view>

        <!-- 社会经济信息 -->
        <view class="mb-[32rpx]">
          <text class="text-[36rpx] font-bold text-blue-600 mb-[24rpx] block">社会经济信息</text>

          <PickerInput v-model="form.eduType" :columns="eduTypeOptions" label="文化程度" prop="eduType" placeholder="请选择文化程度" />

          <PickerInput v-model="form.jobType" :columns="jobTypeOptions" label="职业" prop="jobType" placeholder="请选择职业" />

          <PickerInput v-model="form.marriType" :columns="marriTypeOptions" label="婚姻状况" prop="marriType" placeholder="请选择婚姻状况" />

          <nut-form-item label="工作单位/学校" prop="workPlace" class="mb-[32rpx]">
            <nut-input v-model="form.workPlace" placeholder="请输入工作单位或学校" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>

          <nut-form-item label="医疗费用支付方式" prop="payType" class="mb-[32rpx]">
            <nut-input v-model="form.payType" placeholder="请输入医疗费用支付方式" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>

          <nut-form-item label="其他医疗费用支付方式" class="mb-[32rpx]">
            <nut-input v-model="form.payTypeOther" placeholder="请输入其他支付方式（选填）" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>
        </view>

        <!-- 其他信息 -->
        <view class="mb-[32rpx]">
          <text class="text-[36rpx] font-bold text-blue-600 mb-[24rpx] block">其他信息</text>

          <PickerInput v-model="form.nationality" :columns="nationalityOptions" label="民族" prop="nationality" placeholder="请选择民族" />

          <nut-form-item label="宗教信仰" class="mb-[32rpx]">
            <nut-input v-model="form.religiousBeli" placeholder="请输入宗教信仰（选填）" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>

          <nut-form-item label="出生地" class="mb-[32rpx]">
            <nut-input v-model="form.birthPlace" placeholder="请输入出生地（选填）" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>

          <nut-form-item label="籍贯" class="mb-[32rpx]">
            <nut-input v-model="form.nativePlace" placeholder="请输入籍贯（选填）" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>

          <nut-form-item label="常住地址" class="mb-[32rpx]">
            <nut-input v-model="form.livePlace" placeholder="请输入常住地址（选填）" class="h-[88rpx] text-[32rpx]" />
          </nut-form-item>

          <nut-form-item label="备注" class="mb-[32rpx]">
            <nut-textarea v-model="form.note" placeholder="请输入备注信息（选填）" rows="3" maxlength="200" show-word-limit />
          </nut-form-item>
        </view>

        <view class="mt-[48rpx] flex gap-[24rpx]">
          <nut-button block type="default" class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1"
            @click="resetForm">
            重置表单
          </nut-button>
          <nut-button block type="primary"
            class="h-[96rpx] rounded-[16rpx] text-[32rpx] font-bold shadow flex-1 bg-green-500 hover:bg-green-600 active:bg-green-700"
            :loading="submitting" @click="submitForm">
            {{ submitting ? '保存中...' : '保存信息' }}
          </nut-button>
        </view>
      </nut-form>
    </view>
  </view>
</template>

<script setup lang="ts">
import Taro from '@tarojs/taro'
import { ref, reactive } from 'vue'
import PickerInput from '@/components/PickerInput.vue'

// 表单数据
const form = ref({
  id: '',
  name: '',
  sex: 1,
  birthdate: '',
  idType: 1,
  idNumber: '',
  tel: '',
  eduType: 1,
  jobType: 1,
  marriType: 1,
  workPlace: '',
  payType: '',
  payTypeOther: '',
  nationality: 1,
  religiousBeli: '',
  birthPlace: '',
  nativePlace: '',
  livePlace: '',
  liveType: 1,
  familyDoctor: 0,
  bloodType: '',
  height: '',
  weight: '',
  biosi: '',
  orgName: '',
  orgTel: '',
  recordid: 0,
  note: '',
  valid: 1
})

const formRef = ref()
const submitting = ref(false)
const showForm = ref(false)
const isEdit = ref(false)
const editIndex = ref(-1)
const recordList = ref<any[]>([])

// Calendar related
const showCalendar = ref(false)
const selectedDate = ref(new Date().toISOString().split('T')[0])
const minDate = ref(new Date().toISOString().split('T')[0])
const maxDate = ref(new Date(new Date().getFullYear() + 10, 11, 31).toISOString().split('T')[0])

// 选项数据
const idTypeOptions = [
  [
    { text: '身份证', value: 1 },
    { text: '护照', value: 2 },
    { text: '军官证', value: 3 },
    { text: '其他', value: 4 }
  ]
]

const eduTypeOptions = [
  [
    { text: '文盲或半文盲', value: 1 },
    { text: '小学', value: 2 },
    { text: '初中', value: 3 },
    { text: '高中/中专', value: 4 },
    { text: '大专', value: 5 },
    { text: '本科', value: 6 },
    { text: '研究生及以上', value: 7 }
  ]
]

const jobTypeOptions = [
  [
    { text: '国家机关、党群组织、企业、事业单位负责人', value: 1 },
    { text: '专业技术人员', value: 2 },
    { text: '办事人员和有关人员', value: 3 },
    { text: '商业、服务业人员', value: 4 },
    { text: '农、林、牧、渔业生产人员', value: 5 },
    { text: '生产、运输设备操作人员及有关人员', value: 6 },
    { text: '军人', value: 7 },
    { text: '不便分类的其他从业人员', value: 8 },
    { text: '无职业', value: 9 }
  ]
]

const marriTypeOptions = [
  [
    { text: '未婚', value: 1 },
    { text: '已婚', value: 2 },
    { text: '丧偶', value: 3 },
    { text: '离婚', value: 4 },
    { text: '未说明', value: 5 }
  ]
]

const nationalityOptions = [
  [
    { text: '汉族', value: 1 },
    { text: '蒙古族', value: 2 },
    { text: '回族', value: 3 },
    { text: '藏族', value: 4 },
    { text: '维吾尔族', value: 5 },
    { text: '苗族', value: 6 },
    { text: '彝族', value: 7 },
    { text: '壮族', value: 8 },
    { text: '布依族', value: 9 },
    { text: '朝鲜族', value: 10 },
    { text: '满族', value: 11 },
    { text: '侗族', value: 12 },
    { text: '瑶族', value: 13 },
    { text: '白族', value: 14 },
    { text: '土家族', value: 15 },
    { text: '哈尼族', value: 16 },
    { text: '哈萨克族', value: 17 },
    { text: '傣族', value: 18 },
    { text: '黎族', value: 19 },
    { text: '傈僳族', value: 20 },
    { text: '佤族', value: 21 },
    { text: '畲族', value: 22 },
    { text: '高山族', value: 23 },
    { text: '拉祜族', value: 24 },
    { text: '水族', value: 25 },
    { text: '东乡族', value: 26 },
    { text: '纳西族', value: 27 },
    { text: '景颇族', value: 28 },
    { text: '柯尔克孜族', value: 29 },
    { text: '土族', value: 30 },
    { text: '达斡尔族', value: 31 },
    { text: '仫佬族', value: 32 },
    { text: '羌族', value: 33 },
    { text: '布朗族', value: 34 },
    { text: '撒拉族', value: 35 },
    { text: '毛南族', value: 36 },
    { text: '仡佬族', value: 37 },
    { text: '锡伯族', value: 38 },
    { text: '阿昌族', value: 39 },
    { text: '普米族', value: 40 },
    { text: '塔吉克族', value: 41 },
    { text: '怒族', value: 42 },
    { text: '乌孜别克族', value: 43 },
    { text: '俄罗斯族', value: 44 },
    { text: '鄂温克族', value: 45 },
    { text: '德昂族', value: 46 },
    { text: '保安族', value: 47 },
    { text: '裕固族', value: 48 },
    { text: '京族', value: 49 },
    { text: '塔塔尔族', value: 50 },
    { text: '独龙族', value: 51 },
    { text: '鄂伦春族', value: 52 },
    { text: '赫哲族', value: 53 },
    { text: '门巴族', value: 54 },
    { text: '珞巴族', value: 55 },
    { text: '基诺族', value: 56 },
    { text: '其他', value: 57 }
  ]
]

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入姓名' }
  ],
  sex: [
    { required: true, message: '请选择性别' }
  ],
  idNumber: [
    { required: true, message: '请输入证件号码' }
  ],
  tel: [
    { required: true, message: '请输入电话号码' }
  ]
})

// 获取文本显示
const getSexText = (value: number) => {
  return value === 1 ? '男' : value === 0 ? '女' : '未知'
}



// 选择器确认事件
const onCalendarConfirm = (param: any) => {
  console.log('Calendar confirm param:', param)

  let dateStr = ''

  // 将proxy数组转换为普通数组
  const normalArray = Array.isArray(param) ? [...param] : param

  // 处理不同的参数格式
  if (typeof normalArray === 'string') {
    dateStr = normalArray
  } else if (normalArray && normalArray.selectedDate) {
    dateStr = normalArray.selectedDate
  } else if (normalArray && normalArray.date) {
    dateStr = normalArray.date
  } else if (Array.isArray(normalArray) && normalArray.length >= 4) {
    // 日历返回数组格式: [year, month, day, fullDate, dayOfWeek]
    // 使用索引3获取完整日期字符串 (2025-08-14)
    dateStr = normalArray[3].toString()
  } else if (Array.isArray(normalArray) && normalArray.length >= 3) {
    // 如果没有完整日期，手动构建
    const year = normalArray[0].toString()
    const month = normalArray[1].toString().padStart(2, '0')
    const day = normalArray[2].toString().padStart(2, '0')
    dateStr = `${year}-${month}-${day}`
  }

  console.log('Processed date:', dateStr)

  if (dateStr) {
    // 强制更新表单数据
    form.value.birthdate = dateStr
    selectedDate.value = dateStr

    // 添加调试信息
    console.log('Form birthdate after assignment:', form.value.birthdate)
    console.log('SelectedDate after assignment:', selectedDate.value)

    // 强制触发响应式更新
    form.value = { ...form.value }
  }

  showCalendar.value = false
}



// 新增记录
const addRecord = () => {
  isEdit.value = false
  showForm.value = true
  resetFormData()
}

// 编辑记录
const editRecord = (record: any, index: number) => {
  isEdit.value = true
  editIndex.value = index
  showForm.value = true
  // 直接赋值
  form.value = { ...record }

  // 设置日历选中日期
  selectedDate.value = record.birthdate || ''
}

// 删除记录
const deleteRecord = (index: number) => {
  Taro.showModal({
    title: '确认删除',
    content: '确定要删除这条记录吗？',
    success: (res) => {
      if (res.confirm) {
        recordList.value.splice(index, 1)
        Taro.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    }
  })
}

// 取消表单
const cancelForm = () => {
  showForm.value = false
  resetFormData()
}

// 重置表单数据
const resetFormData = () => {
  form.value = {
    id: '',
    name: '',
    sex: 1,
    birthdate: '',
    idType: 1,
    idNumber: '',
    tel: '',
    eduType: 1,
    jobType: 1,
    marriType: 1,
    workPlace: '',
    payType: '',
    payTypeOther: '',
    nationality: 1,
    religiousBeli: '',
    birthPlace: '',
    nativePlace: '',
    livePlace: '',
    liveType: 1,
    familyDoctor: 0,
    bloodType: '',
    height: '',
    weight: '',
    biosi: '',
    orgName: '',
    orgTel: '',
    recordid: 0,
    note: '',
    valid: 1
  }
  selectedDate.value = ''
}

// 重置表单
const resetForm = () => {
  Taro.showModal({
    title: '确认重置',
    content: '确定要重置表单吗？所有已填写的信息将被清空。',
    success: (res) => {
      if (res.confirm) {
        resetFormData()
        Taro.showToast({
          title: '表单已重置',
          icon: 'success'
        })
      }
    }
  })
}

// 提交表单
const submitForm = async () => {
  try {
    submitting.value = true

    await formRef.value.validate()

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1500))

    if (isEdit.value) {
      // 编辑模式 - 直接保存，不需要转换
      recordList.value[editIndex.value] = { ...form.value }
      Taro.showToast({
        title: '修改成功',
        icon: 'success'
      })
    } else {
      // 新增模式 - 直接保存，不需要转换
      const saveData = {
        ...form.value,
        id: Date.now().toString()
      }
      recordList.value.push(saveData)
      Taro.showToast({
        title: '添加成功',
        icon: 'success'
      })
    }

    showForm.value = false
    resetFormData()

  } catch (error) {
    Taro.showToast({
      title: '请完善必填信息',
      icon: 'error'
    })
  } finally {
    submitting.value = false
  }
}

// 页面加载时获取数据
Taro.useLoad(() => {
  // 这里可以调用API获取数据
  console.log('页面加载，获取社会经济学信息数据')
})
</script>